// rxr
import {
  Toast
} from "react-vant"

const initialState = {
  arr: [], // 渲染列表的数组
  pullarr:[],
  shoparr: JSON.parse(localStorage.getItem("shopcar"))||[] ,// 购物车的数组,
  flagall: eval(localStorage.getItem("flagall")) || false ,// 控制全选的状态
  addressArr:[
    {
      name:"张三",
      address:"北京市昌平区",
      phone:12345678901
    }
  ]
}

let shopreducer = (state = initialState, {
  type,
  payload,
  payload1,
}) => {
  let newobj = JSON.parse(JSON.stringify(state))
  switch (type) {

    case "getlist":
      newobj.arr = payload
      return newobj
    case "addshop":
      // 要做判断，已经加入过购物车的不能假如购物车，没有加入购物车的可以加入
      let findINDEX = newobj.shoparr.findIndex((item, index) => {
        return item.id === payload.id
      })
      if (findINDEX !== -1) {
        Toast.info("您已经加入购物车了")
      } else {
        newobj.shoparr.push(payload)
      }
      localStorage.setItem("shopcar",JSON.stringify(newobj.shoparr))
      return newobj
    case "addFn":
      newobj.shoparr.forEach(element => {
        if (element.id === payload) {
          element.num++
        }
      });
      localStorage.setItem("shopcar",JSON.stringify(newobj.shoparr))
      return newobj
    case "delFn":
      newobj.shoparr.forEach(element => {
        if (element.id === payload) {
          element.num--
          if (element.num <= 1) {
            element.num = 1;
            Toast.info("不能在减去了")
          }
        }
      });
      localStorage.setItem("shopcar",JSON.stringify(newobj.shoparr))
      return newobj
    case "checkitem":
      newobj.shoparr.forEach(element => {
        if (element.id === payload) {
          element.flag = !element.flag
        }
      });
      newobj.flagall = newobj.shoparr.every(item=>item.flag) // every返回一个布尔值，如果都为真，返回的值为真，如果有以项为假，返回的为假
      localStorage.setItem("flagall",newobj.flagall.toString())
      localStorage.setItem("shopcar",JSON.stringify(newobj.shoparr))
      return newobj
    case "changeall" :
      newobj.flagall = !newobj.flagall ;
      newobj.shoparr.forEach(element => {
       
          element.flag =  newobj.flagall
       
      });
      localStorage.setItem("flagall",newobj.flagall.toString())
      localStorage.setItem("shopcar",JSON.stringify(newobj.shoparr))
      return newobj
    case "addaddressfn" :
        newobj.addressArr.push(payload)
        return newobj
    case "delFn1" :
      newobj.addressArr.splice(payload, 1)
      return newobj
    case "editaddressfn" :
      newobj.addressArr.splice(payload1, 1,payload)
      return newobj
    case "getpulllist":
      if (payload1) {
        let newpuallarr = [...newobj.pullarr,...payload]
        newobj.pullarr = newpuallarr
      } else {
        newobj.pullarr = payload
      }
    
      return newobj
    default:
      return state
  }

}
export default shopreducer